package com.example.protocol;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.google.protobuf.InvalidProtocolBufferException;
import com.googlecode.protobuf.format.JsonFormat;
import com.zte.conn.parser.base.protobuf.EventPackInfo;
import com.zte.conn.parser.base.protobuf.ParsedMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.List;

public class ProcotolApplication {


    public void readQt() throws IOException {

        long s = LocalDateTime.of(2019, 7, 1, 0, 0, 0).toEpochSecond(ZoneOffset.UTC) * 1000;
        long e = LocalDateTime.of(2019, 7, 1, 0, 0, 0).toEpochSecond(ZoneOffset.UTC) * 1000;

        BufferedWriter writer = Files.newBufferedWriter(Paths.get("out.csv"));
        Files.readAllLines(Paths.get("")).forEach(deviceId -> {
            String url = String.format("http://120.78.173.249:8087/car/list/originalData/%d/%d/%d?deviceId=%s", s, e, Integer.MAX_VALUE, deviceId);
            String json = HttpUtils.getJson(url, Collections.singletonMap("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MTU2NzY1Mzk2MSwiaWF0IjoxNTY3MDQ5MTYxfQ.3uVhmf4OSKjDyBNgg4spphiRGUqwgi1mbJIGtcOxZ4WtUNY7_W29-4ZFOFEMyePrWq953dAtjk7C2iLwT3amxQ"));
            if(json != null && !json.isEmpty()) {
                int total = 0;
                JsonArray array = new JsonParser().parse(json).getAsJsonObject().get("data").getAsJsonArray();
                for (int i = 0; i < array.size(); i++) {
                    total += array.get(i).getAsJsonObject().get("data").getAsString().length();
                }
                try {
                    writer.write(String.format("%s\t%d", deviceId, total / 2));
                    writer.newLine();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
    }

    public void readGSensor() throws IOException {

        List<String> lines = Files.readAllLines(Paths.get("/Users/linxy/Downloads/869374040253675-GSensonr.csv"));

//        List<String> lines = Files.readAllLines(Paths.get("/Users/linxy/Downloads/data (3).csv"));

        BufferedWriter bw = Files.newBufferedWriter(Paths.get("/Users/linxy/Downloads/abc-out.txt"));


        for (int k = 1; k < lines.size(); k++) {


            String line = lines.get(k);

            line = line.substring(line.indexOf("5555"));


            if (line.isEmpty()) {
                continue;
            }
//            String[] values = line.split(",'");
//            if (values.length != 2) {
//                continue;
//            }
            ByteBuf buf = Unpooled.wrappedBuffer(ByteBufUtil.decodeHexDump(line));

            String dump = ByteBufUtil.hexDump(buf);
            System.out.println(ByteBufUtil.hexDump(buf));

            buf.skipBytes(26);


            long collectTime = buf.readUnsignedInt() * 1000L;
            collectTime += buf.readUnsignedShort();


            int bits = buf.readUnsignedByte();
            int totalPackageCount = (bits & 0xf0) >>> 4;
            int curPackageNo = bits & 0x0f;
            int eventType = buf.readUnsignedByte();

            /**
             * 2018-05-21 新增一个字节frequence,代表该包数据频率(根据最高位)
             * eg : 10001000-->频率为1/8Hz;frequence=1/(1/8)=8000ms
             *      00000101-->频率为5Hz;frequence=1000/5=200ms
             */
            int freBit = buf.readByte();
            int freTop = (freBit & 0x80) >> 7;
            int freNum = freBit & 0x7f;

            int frequence = freNum * 1000;
            if (freTop == 0) {
                frequence = 1000 / freNum;
            }


            // 预留字节
            buf.skipBytes(1);

            // 陀螺仪单位(取值1-5)
            int rateUnit = buf.readUnsignedByte();

            int count = buf.readUnsignedByte();

//            TrackerGSensor.trackerGSensor.Builder trackerGSensor = TrackerGSensor.trackerGSensor.newBuilder()
//                    .setCollectTime(collectTime)
//                    .setTotalPackage(totalPackageCount)
//                    .setCurPackageNo(curPackageNo)
//                    .setEventType(eventType)
//                    .setFrequence(frequence)
//                    .setRateUnit(rateUnit);

            List<LocalDateTime> ts= new ArrayList<>(count);

            System.out.println(collectTime);
            System.out.println(frequence);

            for (int i = 0; i < count; ++i) {
                int x0 = buf.readShort();
                int y0 = buf.readShort();
                int z0 = buf.readShort();

                int x1 = buf.readShort();
                int y1 = buf.readShort();
                int z1 = buf.readShort();

//                System.out.println(collectTime + i * frequence);

                LocalDateTime ld = Instant.ofEpochMilli(collectTime + (i * frequence)).atZone(ZoneId.systemDefault()).toLocalDateTime();


                ts.add(ld);
                System.out.println(collectTime + (i * frequence) + " ==> " + ld);
//                System.out.println(collectTime + i * frequence + " " + i * frequence + " " + ld);


                int lat = buf.readUnsignedMedium();
                int lng = (int) ((buf.getUnsignedInt(buf.readerIndex()) & 0xffffff80) >>> 7);
                buf.skipBytes(3);

                bits = buf.readUnsignedByte();
                int lngFlag = (bits & 0x40) >>> 6;
                int latFlag = (bits & 0x20) >>> 5;
                int realTime = (bits & 0x10) >>> 4;

                buf.skipBytes(1); // 预留

//                TrackerGSensor.trackerGSensor.Gps.Builder gps = TrackerGSensor.trackerGSensor.Gps.newBuilder()
//                        .setLat(lat)
//                        .setLng(lng)
//                        .setLatFlag(latFlag == 1)
//                        .setLngFlag(lngFlag == 1)
//                        .setRealTime(realTime == 1);
//
//                TrackerGSensor.trackerGSensor.Data.Builder data = TrackerGSensor.trackerGSensor.Data.newBuilder()
//                        .setX0Axial(x0)
//                        .setY0Axial(y0)
//                        .setZ0Axial(z0)
//                        .setX1Axial(x1)
//                        .setY1Axial(y1)
//                        .setZ1Axial(z1)
//                        .setGps(gps);
//
//                trackerGSensor.addData(data);
            }

            bw.write(dump);

            for (int i = ts.size() - 1; i >= 0; i--) {
//                System.out.println(ts.get(i));

                bw.write(ts.get(i).toString());
                bw.newLine();
            }

        }


        bw.close();
    }


    public static void parseParsedMessage() throws InvalidProtocolBufferException {

        ParsedMessage.parsedMessage msg = ParsedMessage.parsedMessage.parseFrom(ByteBufUtil.decodeHexDump("0a0f38363938383430343030303033373110c8c5b7f9cf2d18e6ceb7f9cf2d202128e2dc2a32cd020a280a0f3836393838343034303030303337311003180320c8c5b7f9cf2d28e6ceb7f9cf2d3203322e3112110a0f3836393838343034303030303337312288010a280a0f3836393838343034303030303337311003181020e0bdb7f9cf2d28e6ceb7f9cf2d3203322e3112110a0f38363938383430343030303033373119000000602f21414021000000c0ab355b402d0000000035000000003d0000cb43400c4d0000803f559a99193f5dcdcc4c3f60016800b801e0bdb7f9cf2dc00100c80101e00124e801804830e2dc2a3a0e0a0637303030303210e2dc2a1804625b225928c8c5b7f9cf2d32500a280a0f3836393838343034303030303337311003180320c8c5b7f9cf2d28e6ceb7f9cf2d3203322e3112110a0f3836393838343034303030303337311801220f08001000181220012a0550303031326a12e6b1bde8bda6e78684e781abe4b88ae68aa5"));


        System.out.println(new JsonFormat().printToString(msg));

        System.out.println(new JsonFormat().printToString(EventPackInfo.eventPackInfo.parseFrom(msg.getMessageContent())));


        ParsedMessage.parsedMessage msg1 = ParsedMessage.parsedMessage.parseFrom(ByteBufUtil.decodeHexDump("0a0f38363938383430343030303033373110c8c5b7f9cf2d18e6ceb7f9cf2d202128e2dc2a32d0020a280a0f3836393838343034303030303337311003180320c8c5b7f9cf2d28e6ceb7f9cf2d3203322e3112110a0f383639383834303430303030333731228b010a280a0f3836393838343034303030303337311003181020e0bdb7f9cf2d28e6ceb7f9cf2d3203322e3112110a0f38363938383430343030303033373119000000602f21414021000000c0ab355b402d0000000035000000003d0000cb43400c4d0000803f559a99193f5dcdcc4c3f60016800b801e0bdb7f9cf2dc00100c80101e00124e8018048f0010130e2dc2a3a0e0a0637303030303210e2dc2a1804625b225928c8c5b7f9cf2d32500a280a0f3836393838343034303030303337311003180320c8c5b7f9cf2d28e6ceb7f9cf2d3203322e3112110a0f3836393838343034303030303337311801220f08001000181220012a0550303031326a12e6b1bde8bda6e78684e781abe4b88ae68aa5"));


        System.out.println(new JsonFormat().printToString(msg1));

        System.out.println(new JsonFormat().printToString(EventPackInfo.eventPackInfo.parseFrom(msg1.getMessageContent())));

    }


    public static void main(String[] args) throws IOException {

        parseParsedMessage();

    }

}
